﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace DeskFund
{
    public class RequestHelper
    {
        /// <summary>
        /// 添加记录时调用
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Context"></param>
        /// <returns></returns>
        public static RequestMessage RequestPost(string Url, string Context)
        {
            RequestMessage msg = new RequestMessage();
            Uri url = new Uri(Url);
            byte[] reqbytes = Encoding.ASCII.GetBytes(Context);
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                //req.ContentType = "application/json;charset=UTF-8";
                req.ContentType = "text/xml;charset=UTF-8";
                req.ContentLength = reqbytes.Length;
                Stream stm = req.GetRequestStream();
                stm.Write(reqbytes, 0, reqbytes.Length);

                stm.Close();
                HttpWebResponse wr = (HttpWebResponse)req.GetResponse();
                if (wr.StatusCode == HttpStatusCode.OK || wr.StatusCode == HttpStatusCode.Created)
                {
                    Stream stream = wr.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8"));
                    msg.Message = reader.ReadToEnd();
                    stream.Close();
                    reader.Close();
                }
                msg.Status = wr.StatusCode;
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    msg.Status = ((HttpWebResponse)e.Response).StatusCode;
                }
                msg.Message = e.Message;
            }
            catch (Exception e)
            {
                msg.Message = e.Message;
            }
            return msg;
        }

        /// <summary>
        /// 修改记录时调用
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Context"></param>
        /// <returns></returns>
        public static RequestMessage RequestPut(string Url, string Context)
        {
            RequestMessage msg = new RequestMessage();
            Uri url = new Uri(Url);
            byte[] reqbytes = Encoding.ASCII.GetBytes(Context);
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "PUT";
                req.ServicePoint.Expect100Continue = false;
                //req.AllowWriteStreamBuffering = false;

                //req.ProtocolVersion = Version.Parse("1.0");

                //req.AllowWriteStreamBuffering = false;
                //req.AllowAutoRedirect = false;
                req.ContentType = "text/xml;charset=UTF-8";
                req.ContentLength = reqbytes.Length;
                Stream stm = req.GetRequestStream();
                stm.Write(reqbytes, 0, reqbytes.Length);

                stm.Close();
                HttpWebResponse wr = (HttpWebResponse)req.GetResponse();
                if (wr.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = wr.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8"));
                    msg.Message = reader.ReadToEnd();
                    stream.Close();
                    reader.Close();
                }
                msg.Status = wr.StatusCode;
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    msg.Status = ((HttpWebResponse)e.Response).StatusCode;
                }
                msg.Message = e.Message;
            }
            catch (Exception e)
            {
                msg.Message = e.Message;
            }
            return msg;
        }

        /// <summary>
        /// 查询记录时调用
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static RequestMessage RequestGet(string Url)
        {
            RequestMessage msg = new RequestMessage();
            Uri url = new Uri(Url);//Uri类 提供统一资源标识符 (URI) 的对象表示形式和对 URI 各部分的轻松访问。就是处理url地址
            try
            {
                HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(url);//根据url地址创建HTTpWebRequest对象参数设置
                httprequest.Method = "GET";
                #region 参数设置
                //---------------------------------------------设定一些参数（不必要可以）
                //httprequest.KeepAlive = false;//持久连接设置为false
                //httprequest.ProtocolVersion = HttpVersion.Version11;// 网络协议的版本
                //httprequest.Proxy = WebProxy.GetDefaultProxy();//服务器代理
                //httprequest.ContentType = "application/x-www-form-urlencoded";//http 头
                //httprequest.AllowAutoRedirect = true;
                //httprequest.MaximumAutomaticRedirections = 10;
                //httprequest.Timeout = 30000;//设定超时十秒（毫秒）
                //httprequest.UserAgent = "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1)"; //浏览器
                //=================================================
                #endregion
                httprequest.Timeout = 10000;//设定超时5分钟（毫秒）
                HttpWebResponse response = (HttpWebResponse)httprequest.GetResponse();//使用HttpWebResponse获取请求的还回值
                Stream steam = response.GetResponseStream();//从还回对象中获取数据流
                StreamReader reader = new StreamReader(steam, Encoding.GetEncoding("UTF-8"));//读取数据Encoding.GetEncoding("gb2312")指编码是gb2312，不让中文会乱码的
                msg.Status = response.StatusCode;
                msg.Message = reader.ReadToEnd();
                reader.Close();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    msg.Status = ((HttpWebResponse)e.Response).StatusCode;
                }
                msg.Message = e.Message;
            }
            catch (Exception e)
            {
                msg.Message = e.Message;
            }
            return msg;
        }

        /// <summary>
        /// 删除记录时调用
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static RequestMessage RequestDelete(string Url)
        {
            RequestMessage msg = new RequestMessage();
            Uri url = new Uri(Url);//Uri类 提供统一资源标识符 (URI) 的对象表示形式和对 URI 各部分的轻松访问。就是处理url地址
            try
            {
                HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(url);//根据url地址创建HTTpWebRequest对象参数设置
                httprequest.Method = "DELETE";
                HttpWebResponse response = (HttpWebResponse)httprequest.GetResponse();//使用HttpWebResponse获取请求的还回值
                Stream steam = response.GetResponseStream();//从还回对象中获取数据流
                StreamReader reader = new StreamReader(steam, Encoding.GetEncoding("UTF-8"));//读取数据Encoding.GetEncoding("gb2312")指编码是gb2312，不让中文会乱码的
                msg.Status = response.StatusCode;
                msg.Message = reader.ReadToEnd();
                reader.Close();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    msg.Status = ((HttpWebResponse)e.Response).StatusCode;
                }
                msg.Message = e.Message;
            }
            catch (Exception e)
            {
                msg.Message = e.Message;
            }
            return msg;
        }
    }

    public class RequestMessage
    {
        /// <summary>
        /// 返回状态
        /// </summary>
        public HttpStatusCode Status { get; set; }
        /// <summary>
        /// 返回消息
        /// </summary>
        public String Message { get; set; }
    }
}
